package com.mdd.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mdd.common.core.PageResult;
import com.mdd.product.entity.ProductSpu;
import com.mdd.product.mapper.ProductSpuMapper;
import com.mdd.product.service.*;
import com.mdd.product.validate.*;
import com.mdd.product.validate.car.CarSpuValidate;
import com.mdd.product.validate.car.SpuSaleValidate;
import com.mdd.product.vo.*;
import com.mdd.store.api.StoreBindingApi;
import com.mdd.store.vo.StoreVo;
import com.mdd.system.vo.SystemAuthAdminInformVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 商品实现类
 *
 * @author LikeAdmin
 */
@Service
public class ProductSpuServiceImpl implements IProductSpuService {

    @Resource
    ProductSpuMapper productSpuMapper;
    @Resource
    IProductSkuService iProductSkuService;
    @Resource
    IProductPropertyService iProductPropertyService;
    @Resource
    IProductPropertyValueService iProductPropertyValueService;
    @Resource
    ILeasingSchemeService iLeasingSchemeService;
    @Resource
    ILeasingSchemeDetailsService iLeasingSchemeDetailsService;
    @Resource
    StoreBindingApi storeBindingApi;


    /**
     * 商品列表
     *
     * @param searchValidate 搜索参数
     * @return PageResult<ProductSpuListedVo>
     * @author LikeAdmin
     */
    @Override
    public PageResult<ProductSpuListedVo> page(ProductSpuSearchValidate searchValidate, SystemAuthAdminInformVo systemAuthAdmin) {
        int page = null != searchValidate ? searchValidate.getPageNo() : 1;
        int limit = null != searchValidate ? searchValidate.getPageSize() : 10;
        LambdaQueryWrapper<ProductSpu> queryWrapper = new LambdaQueryWrapper<>();
        if (Objects.nonNull(searchValidate.getName())) {
            queryWrapper.like(ProductSpu::getName, searchValidate.getName());
        }
        if (!systemAuthAdmin.getDeptIds().equals(1L)) {
            queryWrapper.likeRight(ProductSpu::getDeptCode, systemAuthAdmin.getDeptCode());
        }
        queryWrapper.likeRight(ProductSpu::getDeptCode, systemAuthAdmin.getDeptCode());
        queryWrapper.orderByDesc(ProductSpu::getSort);

        IPage<ProductSpu> iPage = productSpuMapper.selectPage(new Page<>(page, limit), queryWrapper);

        List<ProductSpuListedVo> list = new LinkedList<>();
        for (ProductSpu item : iPage.getRecords()) {
            ProductSpuListedVo vo = new ProductSpuListedVo();
            BeanUtils.copyProperties(item, vo);
            list.add(vo);
        }

        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), list);
    }

    /**
     * 商品列表
     *
     * @param searchValidate 搜索参数
     * @return PageResult<ProductSpuListedVo>
     * @author LikeAdmin
     */
    @Override
    public PageResult<CarSpuListVo> cars(ProductSpuSearchValidate searchValidate, SystemAuthAdminInformVo systemAuthAdmin) {
        int page = null != searchValidate ? searchValidate.getPageNo() : 1;
        int limit = null != searchValidate ? searchValidate.getPageSize() : 10;

        LambdaQueryWrapper<ProductSpu> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(searchValidate.getName())) {
            queryWrapper.like(ProductSpu::getName, searchValidate.getName());
        }
        queryWrapper.eq(ProductSpu::getType,searchValidate.getPType());
        queryWrapper.eq(ProductSpu::getDeptId, systemAuthAdmin.getDeptCode());
        queryWrapper.orderByDesc(ProductSpu::getSort);

        IPage<ProductSpu> iPage = productSpuMapper.selectPage(new Page<>(page, limit), queryWrapper);

        List<CarSpuListVo> list = new LinkedList<>();
        for (ProductSpu item : iPage.getRecords()) {
            CarSpuListVo vo = new CarSpuListVo();
            BeanUtils.copyProperties(item, vo);
            list.add(vo);
        }

        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), list);
    }

    /**
     * 商品列表
     *
     * @return List<ProductSpuListedVo>
     * @author LikeAdmin
     */
    @Override
    public List<ProductSpuListedVo> list(SystemAuthAdminInformVo systemAuthAdmin) {
        LambdaQueryWrapper<ProductSpu> productWrapper = new LambdaQueryWrapper<>();
        if (!systemAuthAdmin.getDeptIds().equals(1L)) {
            productWrapper.likeRight(ProductSpu::getDeptCode, systemAuthAdmin.getDeptCode());
        }
        List<ProductSpu> data = productSpuMapper.selectList(productWrapper);

        List<ProductSpuListedVo> list = new LinkedList<>();
        for (ProductSpu item : data) {
            ProductSpuListedVo vo = new ProductSpuListedVo();
            BeanUtils.copyProperties(item, vo);
            list.add(vo);
        }
        return list;
    }


    /**
     * 商品详情
     *
     * @param id 主键参数
     * @return ProductSpu
     * @author LikeAdmin
     */
    @Override
    public ProductSpuDetailVo detail(Long id) {
        ProductSpu model = productSpuMapper.selectById(id);

        Assert.notNull(model, "商品spu数据不存在");

        ProductSpuDetailVo vo = new ProductSpuDetailVo();
        BeanUtils.copyProperties(model, vo);

        List<ProductSkuListedVo> list = iProductSkuService.list(id);
        vo.setSkus(list);
        vo.setPropertyList(iProductPropertyService.list(id));
        vo.setLeasingSchemes(iLeasingSchemeService.list(id));
        return vo;
    }

    @Override
    public CarSpuDetailVo carSpuDetail(Long id) {
        ProductSpu model = productSpuMapper.selectById(id);

        Assert.notNull(model, "商品spu数据不存在");

        CarSpuDetailVo vo = new CarSpuDetailVo();
        BeanUtils.copyProperties(model, vo);

        List<StoreVo> stores = storeBindingApi.stores(model.getId());
        vo.setStores(stores);

        return vo;
    }

    /**
     * 商品新增
     *
     * @param createValidate 参数
     * @author LikeAdmin
     */
    @Override
    @Transactional
    public void add(ProductSpuCreateValidate createValidate, SystemAuthAdminInformVo systemAuthAdmin) {
        ProductSpu model = new ProductSpu();
        model.setName(createValidate.getName());
        model.setDeptId(systemAuthAdmin.getDeptIds());
        model.setDeptCode(systemAuthAdmin.getDeptCode());

        model.setIntroduction(createValidate.getIntroduction());
        model.setDescription(createValidate.getDescription());
        model.setCategoryId(createValidate.getCategoryId());
        model.setPicUrl(createValidate.getPicUrl());
        model.setSliderPicUrls(createValidate.getSliderPicUrls());
        model.setVideoUrl(createValidate.getVideoUrl());
        model.setSort(createValidate.getSort());
        model.setStatus(createValidate.getStatus());
        model.setSpecType(createValidate.getSpecType());
        model.setPrice(createValidate.getPrice());
        model.setMarketPrice(createValidate.getMarketPrice());
        model.setCostPrice(createValidate.getCostPrice());
        model.setStock(createValidate.getStock());
        model.setSalesCount(createValidate.getSalesCount());
        productSpuMapper.insert(model);
        ///保存SKU
        Assert.notNull(createValidate.getSkus(), "sku数据不能为空！");
        createValidate.getSkus().forEach(productSkuCreateValidate -> {
            productSkuCreateValidate.setSpuId(model.getId());
            productSkuCreateValidate.setSalesCount(0);
            iProductSkuService.add(productSkuCreateValidate);
        });
        //保存属性
        Assert.notNull(createValidate.getPropertyList(), "propertyList数据不能为空！");
        createValidate.getPropertyList().forEach(productPropertyCreateValidate -> {
            productPropertyCreateValidate.setSpuId(model.getId());
            Long id = iProductPropertyService.add(productPropertyCreateValidate);
            if (Objects.nonNull(productPropertyCreateValidate.getPropertyValues())) {
                productPropertyCreateValidate.getPropertyValues().forEach(productPropertyValueCreateValidate -> {
                    productPropertyValueCreateValidate.setPropertyId(id);
                    iProductPropertyValueService.add(productPropertyValueCreateValidate);
                });
            }
        });
        //保存租赁方案
        Assert.notNull(createValidate.getLeasingSchemes(), "租赁方案不能为空！");
        createValidate.getLeasingSchemes().forEach(leasingSchemeCreateValidate -> {
            leasingSchemeCreateValidate.setSpuId(model.getId());
            Long schemeId = iLeasingSchemeService.add(leasingSchemeCreateValidate);
            if (Objects.nonNull(leasingSchemeCreateValidate.getSchemeDetails())) {
                leasingSchemeCreateValidate.getSchemeDetails().forEach(leasingSchemeDetailsCreateValidate -> {

                    leasingSchemeDetailsCreateValidate.setSpuId(model.getId());
                    leasingSchemeDetailsCreateValidate.setSchemeId(schemeId);
                    iLeasingSchemeDetailsService.add(leasingSchemeDetailsCreateValidate);
                });
            }
        });
    }

    @Override
    public void addCarSpu(CarSpuValidate carSpuValidate, SystemAuthAdminInformVo systemAuthAdmin) {
        ProductSpu model = new ProductSpu();
        BeanUtils.copyProperties(carSpuValidate,model);
        model.setDeptId(systemAuthAdmin.getDeptIds());
        model.setDeptCode(systemAuthAdmin.getDeptCode());
        model.setStatus(1);
        model.setType(1);
        productSpuMapper.insert(model);
        if ( carSpuValidate.getStores()!=null && carSpuValidate.getStores().length > 0) {
            //绑定商品
            storeBindingApi.sava(model.getId(), Arrays.asList(carSpuValidate.getStores()));
        }
    }

    @Transactional
    @Override
    public void editCarSpu(CarSpuValidate carSpuValidate) {
        ProductSpu model = productSpuMapper.selectById(carSpuValidate.getId());
        Assert.notNull(model, "商品spu数据不存在!");
        BeanUtils.copyProperties(carSpuValidate,model);
        productSpuMapper.updateById(model);
        if (Objects.nonNull(carSpuValidate.getStores())) {
            //清理，并绑定商品
            storeBindingApi.savaOrDel(model.getId(), Arrays.asList(carSpuValidate.getStores()));
        }
    }

    /**
     * 商品编辑
     *
     * @param updateValidate 参数
     * @author LikeAdmin
     */
    @Transactional
    @Override
    public void edit(ProductSpuUpdateValidate updateValidate) {
        ProductSpu model = productSpuMapper.selectById(updateValidate.getId());

        Assert.notNull(model, "商品spu数据不存在!");

        model.setId(updateValidate.getId());
        model.setName(updateValidate.getName());
        model.setIntroduction(updateValidate.getIntroduction());
        model.setDescription(updateValidate.getDescription());
        model.setCategoryId(updateValidate.getCategoryId());
        model.setPicUrl(updateValidate.getPicUrl());
        model.setSliderPicUrls(updateValidate.getSliderPicUrls());
        model.setVideoUrl(updateValidate.getVideoUrl());
        model.setSort(updateValidate.getSort());
        model.setStatus(updateValidate.getStatus());
        model.setSpecType(updateValidate.getSpecType());
        model.setPrice(updateValidate.getPrice());
        model.setMarketPrice(updateValidate.getMarketPrice());
        model.setCostPrice(updateValidate.getCostPrice());
        model.setStock(updateValidate.getStock());
        model.setSalesCount(updateValidate.getSalesCount());
        productSpuMapper.updateById(model);

        //保存SKU
        if (Objects.nonNull(updateValidate.getSkus())) {
            //删除本次不存在的sku
            Set<Long> idSet = updateValidate.getSkus().stream().map(ProductSkuUpdateValidate::getId).filter(Objects::nonNull).collect(Collectors.toSet());

            iProductSkuService.delSkuBySpuIdAndSku(updateValidate.getId(), idSet);

            updateValidate.getSkus().forEach(productSkuUpdateValidate -> {
                if (Objects.isNull(productSkuUpdateValidate.getId())) {
                    ProductSkuCreateValidate productSkuCreateValidate = new ProductSkuCreateValidate();
                    BeanUtils.copyProperties(productSkuUpdateValidate, productSkuCreateValidate);
                    productSkuCreateValidate.setSpuId(updateValidate.getId());
                    iProductSkuService.add(productSkuCreateValidate);
                } else {
                    productSkuUpdateValidate.setSpuId(updateValidate.getId());
                    iProductSkuService.edit(productSkuUpdateValidate);
                }

            });

        }
        //保存属性
        if (Objects.nonNull(updateValidate.getPropertyList())) {

            Set<Long> idSet = updateValidate.getPropertyList().stream().map(ProductPropertyUpdateValidate::getId).filter(Objects::nonNull).collect(Collectors.toSet());
            //查询需删除的name列表
            List<Object> needDeleteIds = iProductPropertyService.listDeletedIds(updateValidate.getId(), idSet);
            if (!needDeleteIds.isEmpty()) {
                iProductPropertyValueService.delByPropertyIds(needDeleteIds);
                iProductPropertyService.delIds(needDeleteIds);
            }
            updateValidate.getPropertyList().forEach(productPropertyUpdateValidate -> {
                Long propertyId;
                if (Objects.isNull(productPropertyUpdateValidate.getId())) {
                    ProductPropertyCreateValidate productSkuUpdateValidate = new ProductPropertyCreateValidate();
                    BeanUtils.copyProperties(productPropertyUpdateValidate, productSkuUpdateValidate);
                    productSkuUpdateValidate.setSpuId(model.getId());
                    propertyId = iProductPropertyService.add(productSkuUpdateValidate);
                } else {
                    propertyId = productPropertyUpdateValidate.getId();
                    productPropertyUpdateValidate.setSpuId(model.getId());
                    iProductPropertyService.edit(productPropertyUpdateValidate);
                }
                if (Objects.nonNull(productPropertyUpdateValidate.getPropertyValues())) {
                    Set<Long> valueIdSet = productPropertyUpdateValidate.getPropertyValues().stream().map(ProductPropertyValueUpdateValidate::getId).filter(Objects::nonNull).collect(Collectors.toSet());
                    iProductPropertyValueService.delByPropertyIdAndNotInValues(productPropertyUpdateValidate.getId(), valueIdSet);
                    productPropertyUpdateValidate.getPropertyValues().forEach(productPropertyValueUpdateValidate -> {
                        if (Objects.isNull(productPropertyValueUpdateValidate.getId())) {
                            ProductPropertyValueCreateValidate propertyValueCreateValidate = new ProductPropertyValueCreateValidate();
                            BeanUtils.copyProperties(productPropertyValueUpdateValidate, propertyValueCreateValidate);
                            propertyValueCreateValidate.setPropertyId(propertyId);
                            iProductPropertyValueService.add(propertyValueCreateValidate);
                        } else {
                            productPropertyValueUpdateValidate.setPropertyId(propertyId);
                            iProductPropertyValueService.edit(productPropertyValueUpdateValidate);
                        }
                    });
                }
            });
        }
        //保存租赁方案
        if (Objects.nonNull(updateValidate.getLeasingSchemes())) {

            Set<Long> idSet = updateValidate.getLeasingSchemes().stream().map(LeasingSchemeUpdateValidate::getId).filter(Objects::nonNull).collect(Collectors.toSet());
            //查询需删除的name列表
            List<Object> needDeleteIds = iLeasingSchemeService.listDeletedIds(updateValidate.getId(), idSet);
            if (!needDeleteIds.isEmpty()) {
                iLeasingSchemeDetailsService.delBySchemeIds(needDeleteIds);
                iLeasingSchemeService.delIds(needDeleteIds);
            }
            updateValidate.getLeasingSchemes().forEach(leasingSchemeCreateValidate -> {

                Long schemeId;
                if (Objects.isNull(leasingSchemeCreateValidate.getId())) {
                    LeasingSchemeCreateValidate schemeCreateValidate = new LeasingSchemeCreateValidate();
                    BeanUtils.copyProperties(leasingSchemeCreateValidate, schemeCreateValidate);
                    schemeCreateValidate.setSpuId(updateValidate.getId());
                    schemeId = iLeasingSchemeService.add(schemeCreateValidate);
                } else {
                    schemeId = leasingSchemeCreateValidate.getId();
                    leasingSchemeCreateValidate.setSpuId(updateValidate.getId());
                    iLeasingSchemeService.edit(leasingSchemeCreateValidate);
                }
                if (Objects.nonNull(leasingSchemeCreateValidate.getSchemeDetails())) {
                    Set<Long> valueIdSet = leasingSchemeCreateValidate.getSchemeDetails().stream().map(LeasingSchemeDetailsUpdateValidate::getId).filter(Objects::nonNull).collect(Collectors.toSet());
                    iLeasingSchemeDetailsService.delBySchemeIdAndNotInValues(leasingSchemeCreateValidate.getId(), valueIdSet);

                    leasingSchemeCreateValidate.getSchemeDetails().forEach(leasingSchemeDetailsUpdateValidate -> {
                        if (Objects.isNull(leasingSchemeDetailsUpdateValidate.getId())) {
                            LeasingSchemeDetailsCreateValidate schemeDetailsCreateValidate = new LeasingSchemeDetailsCreateValidate();
                            BeanUtils.copyProperties(leasingSchemeDetailsUpdateValidate, schemeDetailsCreateValidate);
                            schemeDetailsCreateValidate.setSchemeId(schemeId);
                            schemeDetailsCreateValidate.setSpuId(updateValidate.getId());
                            iLeasingSchemeDetailsService.add(schemeDetailsCreateValidate);
                        } else {
                            leasingSchemeDetailsUpdateValidate.setSchemeId(schemeId);
                            leasingSchemeDetailsUpdateValidate.setSpuId(updateValidate.getId());
                            iLeasingSchemeDetailsService.edit(leasingSchemeDetailsUpdateValidate);
                        }
                    });
                }
            });
        }
    }

    /**
     * 商品删除
     *
     * @param id 主键ID
     * @author LikeAdmin
     */
    @Transactional
    @Override
    public void del(Long id) {
        ProductSpu model = productSpuMapper.selectById(id);

        Assert.notNull(model, "商品spu数据不存在!");
        //删除商品信息
        productSpuMapper.deleteById(id);
        //删除商品SKU
        iProductSkuService.delSpu(id);
    }

    @Transactional
    @Override
    public void onSale(SpuSaleValidate saleValidate) {
        ProductSpu model = productSpuMapper.selectById(saleValidate.getId());
        Assert.notNull(model, "商品spu数据不存在!");
        model.setStatus(saleValidate.getStatus());

        productSpuMapper.updateById(model);
    }

}
